package com.gizwits.actor
import reactivemongo.api.collections.bson.BSONCollection
import org.json4s._
import org.json4s.JsonDSL._
import org.json4s.jackson.JsonMethods._
import reactivemongo.api._
import reactivemongo.bson._
import scala.concurrent.ExecutionContext.Implicits.global
import scala.util.{Success, Failure}


case  class  Pay(min:Int,max:Int)
case  class Datainfo1(did:String,timestamp:Long,product_key:String,mac:String,ip:String,`type`:String)

case  class Datainfo(did:String,timestamp:Long,product_key:String,mac:String,ip:String,`type`:String,payload: Pay)

object WriteMongo {
  def main(args: Array[String]) {

    // val  json="""{"did": "ux95ZfenN5QDMXMSLEZdWP", "timestamp": 1409107047, "product_key": "5760dd8e0e4c11e4b6c400163e02392a", "mac": "--2642743592", "ip": "182.92.160.95", "type": "dev_online","payload":{"min":100,"max":700} }"""
    val  json="""{"did": "ux95ZfenN5QDMXMSLEZdWP", "timestamp": 1409107047, "product_key": "5760dd8e0e4c11e4b6c400163e02392a", "mac": "--2642743592", "ip": "182.92.160.95", "type": "dev_online"}"""


    val fj=parse(json)
    println(fj)
    implicit val aggHandler0 = Macros.handler[Datainfo1]
    implicit val aggHandler1 = Macros.handler[Pay]
    implicit val aggHandler = Macros.handler[Datainfo]
    val driver = new MongoDriver
    val connection = driver.connection(List("localhost:27017"))
    val db = connection("test")
    val collection = db[BSONCollection]("testjson")
    implicit val formats = DefaultFormats


    fj \ "payload" match {
      case JNothing =>{
        val  future=collection.insert(fj.extract[Datainfo1])

        future.onComplete {
          case Failure(e) => throw e
          case Success(lastError) => {
            println("successfully inserted document with lastError = " + lastError)
          }
        }
      }
      case _ =>{
        val  future=collection.insert(fj.extract[Datainfo])

        future.onComplete {
          case Failure(e) => throw e
          case Success(lastError) => {
            println("successfully inserted document with lastError = " + lastError)
          }
        }
      }

    }



  }
}


